package com.spzx.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Override
    public String submitAlipay(String orderNo) throws AlipayApiException {
        //1.封装支付信息，保存支付信息，返回支付信息
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);

        //2.封装支付参数数据
        // 声明一个map 集合
        HashMap<String, Object> map = new HashMap<>();
        //参数必填项
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        //map.put("total_amount",orderInfo.getTotalAmount());
        map.put("total_amount", "0.01"); //    ！！！！！！！！！！！！！！
        map.put("subject", paymentInfo.getContent());

        //3.调用支付宝支付接口
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //支付宝支付扣款成功后，会回调这两个接口；
        request.setReturnUrl(AlipayConfig.return_payment_url); //同步回调地址，用于通知用户支付成功。不作为最终依据。
        //异步回调地址，支付宝服务器端调用咱们服务器端返回支付数据结果。需要将这些数据更新到支付信息表中，完成额外业务逻辑：例如，修改订单状态，更新支付信息。
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        request.setBizContent(JSON.toJSONString(map));

        //4.获取支付接口返回的form表单，用于打开手机支付宝，弹出密码框进行支付。
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "post");
        String from = response.getBody(); //支付表单
        return from;
    }


    @Override
    public void closePayment(String orderNo) {
        PaymentInfo paymentInfo = paymentInfoService.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo,orderNo));
        if (paymentInfo != null && "0".equals(paymentInfo.getPaymentStatus())) {
            paymentInfo.setPaymentStatus("-1");
            paymentInfoService.updateById(paymentInfo);
        }
    }
}
